// ==UserScript==
// @name         miCase1
// @namespace    liqing
// @version      0.3
// @description  小米催收案件详情获取
// @author       liqing
// @include      https://cs.pt.xiaomi.com/web/*
// @grant        GM_xmlhttpRequest
// @grant        GM_addStyle
// @grant        window.close
// @connect      *
// @updateURL    https://gitee.com/liqing_study/Tampermokey/blob/master/miCase1.js
// ==/UserScript==

var i_contactTab = document.querySelector("#contactTab");
var c_parent, c_parent_childs;
var c_person_info, c_account_info, c_case_info;

//案件页面静态数据
var caseData = {};

//总数据
var sumData = [];
var extJson = {};

//获取url参数
var caseId, urlId2, location_search;
//获取按钮插入位置
var addBtnFlag = false;
var agentId,miId;

var getInfoUrl = "http://10.253.45.73:8601/get_data",
submitInfoUrl="http://10.180.200.50:9016/api/xiaomi/call/upload",
uproadStatusUrl = "http://10.180.200.50:9016/api/xiaomi/call/upload-status";

//数据展示请求参数
var cas_num,cas_name,cas_mov_pho;
var personInfo=[],relationInfo = [];


//案件办理标签页
var caseDetailAction;

//提交总数据开关
var submitFlag = false;
var username;
var orgId = 91;
console.log("小米催收案件提交");

var callInfo = localStorage.getItem("callInfo");
var dialog = callInfo;
//删除轮询的信息避免重复
localStorage.setItem("callInfo","");

//拨打成功展示的信息
setTimeout(function() {
    if (dialog) {
        var dialogList = dialog.split("-");
        alert(`客户:${dialogList[0]}手机号:${ dialogList[1]}通话成功`);
    } else {
        console.log("没有获取到轮询状态中传递的参数");
    }
}, 500);

setTimeout(() => {
    i_contactTab = document.querySelector("#contactTab");
    if (i_contactTab) {
        console.log("小米催收案件获取脚本开始执行");        
        addAlert();
        //总数据提交按钮插入位置
        var c_remark_form = document.querySelectorAll(".remark-form");
        var insertSumBtn = c_remark_form[0];
        var c_username = document.querySelector(".username");
        username = c_username.innerText;

        c_parent = document.querySelector("#caseDetail");
        if (c_parent != null) {
            c_parent_childs = c_parent.querySelectorAll(".row");
        }
        agentId = getCookie("userId") + "#";
        console.log(agentId);
        if (agentId) {
            caseData.agentId = agentId;
        }
        var sidebar = document.querySelector(".navbar");
        

      //获取url参数
      if (!location_search) {
          location_search = window.location.href;
          var qs = location_search.slice((location_search.indexOf("detail/") + 7), location_search.lastIndexOf("/%7B%7D"));
          var argList = qs.split("/");
          caseData.orgId = orgId;
          caseData.caseId = argList[0];
          caseData.customerCode = argList[1];
          // caseData.caseId = 1234;
          // caseData.customerCode = 54321;
      }
      

      if (c_parent == null) {
          c_parent = document.querySelector("#caseDetail");
      }
      c_parent_childs = c_parent.querySelectorAll(".row");
      if (c_parent_childs.length !== 0) {
          //获取静态表数据
          submitAccountData();
          console.log(1)
          getSelfContack();
          
      }
      caseDetailAction = document.querySelector("#caseDetailAction");
    }
}, 3000);

var submitInterval = setInterval(()=>{
  if(submitFlag){
    console.log("开始提交总数据");
    submitSumData();
    clearInterval(submitInterval);
  }
},1000)

//获取加密的手机号
var selfUrl = "https://cs.pt.xiaomi.com/userContact/selfContact?draw=1&start=0&length=10&search%5Bvalue%5D=&search%5Bregex%5D=false";
var realMobileList;
function getSelfContack() {
  let cookie = document.cookie;
  GM_xmlhttpRequest({
    method: "get",
    url: `${selfUrl}&caseId=${caseData.caseId}&mifiId=${caseData.customerCode}`,
    headers: {
      "Accept": "application/json, text/javascript, */*; q=0.01",
      "Accept-Encoding": "gzip, deflate, br",
      "Accept-Language": "zh-CN,zh;q=0.9",
      "Connection": "keep-alive",
      "Cookie": cookie,
      "Host": "cs.pt.xiaomi.com",
      "Referer": "https://cs.pt.xiaomi.com/web/",
      "Sec-Fetch-Mode": "cors",
      "Sec-Fetch-Site": "same-origin",
      "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36",
      "X-Requested-With": "XMLHttpRequest"
    },
    onload: function(res) {
      console.log(res);
      console.log(res.status);
      if (res.status == 200) {
        let responseData = JSON.parse(res.responseText + "");
        console.log(responseData);
        let data = responseData.data;
        realMobileList = data.map((item)=>{
          return item.realMobile;
        });
        console.log(realMobileList);
      }
    },
    onerror: function(err) {
      showAlert("请求错误，请稍后再试");
      console.log(err);
    }
  })
}

function getCookie(cookieName) {
  //将document.cookie保存在变量cookie中
  var cookie = document.cookie;
  //在cookie中查找cookieName的位置保存在i中
  var i = cookie.indexOf(cookieName);
  //如果i等于-1,就返回null
  if (i == -1) {
      return null
  } else { //否则  
      //i+cookieName的长度+1,保存在变量starti中
      var starti = i + cookieName.length + 1;
      //从starti开始查找cookie中下一个;的位置endi
      var endi = cookie.indexOf(";", starti);
      if (endi == -1) { //如果endi是-1
          //截取cookie中starti到结尾的剩余内容,返回
          return cookie.slice(starti);
      } else { //否则
          //截取cookie中starti到endi的内容，返回
          return cookie.slice(starti, endi);
      }
  }
}

//开始获取数据
function submitAccountData() {
  //获取个人信息，总览，案件信息
  getPersonInfoPart();
  getCaseStatus();
  getSumMoneyInfo();
  getPersonInfo(8);
  var caseDatasJson = JSON.stringify(caseData);

  let uproadData ={orgId:orgId,customerId:agentId,xiaomiId:miId};
  let uproadDataJson = JSON.stringify(uproadData);

  GM_xmlhttpRequest({
    method: "POST",
    url: uproadStatusUrl,
    headers: {
        "Content-Type": "application/json"
    },
    data: uproadDataJson,
    onload: function(res) {
        if (res.status == 200) {
            let resonpseData = JSON.parse(res.responseText + "");
            let datas = resonpseData.data;
            if(!datas){
              //获取本人和三方信息
              submitPerson();
            }else{
              let caseClick = localStorage.getItem("autoClick");
              showAlert("该数据已发送");
              if(caseClick){
                localStorage.setItem("autoClick","");
                window.close();
              }
              // alert("该数据已发送");
            }
        }else{
          console.log("请求未成功");
        }
    },
    onerror: function(err) {
        showAlert("请求错误，请稍后再试");
        console.log(err);
    }
});


}

//提交总数据方法
function submitSumData() {
  if (JSON.stringify(caseData) == '{}') {
    showAlert("案件页面静态表没有获取到,请刷新页面");
      return;
  }
  if (!caseData.selfList || !caseData.thirdList) {
      showAlert("本人信息或三方信息没有获取到，请重新获取");
      return;
  }
  if (JSON.stringify(extJson) == '{}') {
      showAlert("扩展数据没有获取到，请刷新页面");
      return;
  }
  caseData.extJson = extJson;
  var sumDataJson = JSON.stringify(caseData);
  caseData = {};
  extJson = {};

  GM_xmlhttpRequest({
      method: "POST",
      url: submitInfoUrl,
      headers: {
          "Content-Type": "application/json"
      },
      data: sumDataJson,
      onload: function(res) {
          if (res.status == 200) {
            showAlert("提交数据成功");
            let caseClick = localStorage.getItem("autoClick");
            if(caseClick){
              localStorage.setItem("autoClick","");
              window.close();
            }
          }
      },
      onerror: function(err) {
          showAlert("请求错误，请稍后再试");
          console.log(err);
      }
  });

}

//个人信息部分获取
function getPersonInfoPart() {
  c_person_info = c_parent_childs[1];
  var title = "personInfoPart";
  var personLi = c_person_info.querySelectorAll("li");

  var personData = {};
  var items = personLi[0].querySelectorAll(".ng-scope");
  var itemsTitle = ['miId', 'name', '', 'sex', ];
  for (let i = 0; i < items.length; i++) {
      if (i !== 2) {
          var spans = items[i].querySelectorAll("span");
          personData[itemsTitle[i]] = spans[1].innerText;
      }
  }
  miId = personData['miId'];
  caseData.xiaomiId = miId;
  caseData.sex = personData['sex'];
  var item2s = personLi[1].querySelectorAll(".ng-scope");
  var idCards = item2s[3].querySelectorAll('span');
  caseData.idCard = idCards[1].innerText;
  let idCard = caseData.idCard;
  cas_mov_pho = idCard.slice(0,idCard.indexOf('*'));
  cas_name = personData.name;

}

//案件信息8 获取
function getPersonInfo(id_index) {
  c_person_info = c_parent_childs[id_index];
  // var title = c_person_info.querySelector(".title").innerText;
  // var title = 'caseInfo';
  var personLi = c_person_info.querySelectorAll("li");

  var personData = {};
  for (let index = 0; index < personLi.length; index++) {
      var items = personLi[index].querySelectorAll(".ng-scope");
      for (let i = 0; i < items.length; i++) {
          var spans = items[i].querySelectorAll("span");
          personData[spans[0].innerText] = spans[1].innerText;
          extJson[spans[0].innerText] = spans[1].innerText;
      }
  }
  // caseData[title] = personData;
  caseData['overdueDays'] = personData['逾期天数'];
  caseData['accountAge'] = personData['当前账龄'];
  caseData['agentName'] = personData['处理人'];
  // caseData['agentId'] = personData['处理人'];
  // caseData['agentId'] = 1231;
}

//案件补充信息案件状态
function getCaseStatus() {
  var table_item = document.querySelector("#extra");
  if (!table_item) {
      caseData['status'] = '';
  }
  var tbody = table_item.querySelector("tbody");
  var trList = tbody.querySelectorAll("tr");
  var caseStatus = trList[0].querySelectorAll('td');
  caseData['status'] = caseStatus[2].innerText;
}

//账务信息总览获取
function getSumMoneyInfo() {
  c_account_info = c_parent_childs[2];
  var sumMoneyInfo = c_account_info.querySelectorAll(".row")[0];
  var itemsLi = sumMoneyInfo.querySelectorAll("li");
  var sumMoneyInfoData = {};
  for (let index1 = 0; index1 < itemsLi.length; index1++) {
      var items = itemsLi[index1].querySelectorAll(".ng-scope");
      for (let index2 = 0; index2 < items.length; index2++) {
          var spans = items[index2].querySelectorAll("span");
          sumMoneyInfoData[spans[0].innerText] = spans[1].innerText;
          extJson[spans[0].innerText] = spans[1].innerText;
      }
  }
  // caseData[title] = sumMoneyInfoData;
  //案件金额获取
  caseData['caseMoney'] = sumMoneyInfoData['总逾期金额'];

}

var delateTime = 1000;
//查看并获取本人三方信息
function submitPerson() {
  showAllClick();
  setTimeout(() => {
          getUserInfo();
          let thirdInfo = i_contactTab.querySelectorAll("li")[1];
          let thirdInfo_a = thirdInfo.querySelector("a");
          thirdInfo_a.click();

          setTimeout(()=>{
            showAllClick();
            setTimeout(getUserInfo,delateTime);
          }, delateTime);
      },delateTime)
}


//获取本人owner&认证联络信息userAdd
function getUserInfo() {
  // var table_id = document.querySelector(id_item);
  var table_type1 = document.querySelector("#owner");
  var table_type2 = document.querySelector("#userAdd");
  var table_item;
  //用户信息标识
  var benren_name = ["name", "relation", "phoneNum", ,"forbidden"];
  var renzeng_name = ["relation", "name", "phoneNum",, "forbidden"];
  var userDataName, isPerson = false;
  if (table_type1 != null) {
      table_item = table_type1;
      userDataName = benren_name;
      isPerson = true;
  } else if (table_type2 != null) {
      table_item = table_type2;
      userDataName = renzeng_name;
      isPerson = false;
  } else {
      console.log("没有获取到个人联系信息的标签");
      return;
  }

  var tbody = table_item.querySelector("tbody");
  var trList = tbody.querySelectorAll("tr");
  var userData = [];
  for (let index = 0; index < trList.length; index++) {
      var tdList = trList[index].querySelectorAll("td");
      var item = {};
      var phoneStr = tdList[2].childNodes[0].textContent;

      if (phoneStr.indexOf("*") > -1) {
          console.log("手机号未完全展开");
          break;
      }
      for (let index1 = 0; index1 < tdList.length; index1++) {
          var s = userDataName[index1];
          if(index1 === 3)
            continue;
          if (index1 === 4) {
              item[s] = tdList[index1].childNodes[0].textContent === '禁止电话' ? 0 : 1;
          } else {

              item[s] = tdList[index1].childNodes[0].textContent;
          }
      }
      var isResert = true;
      for (let i = 0; i < userData.length; i++) {
          if (item["phoneNum"] === userData[i]["phoneNum"]) {
              isResert = false;
              break;
          }

      }
      if (isResert) {
          userData.push(item);
          console.log(userData);
      }

  }
  if (userData.length === 0) {
      alert("没有获取到表3数据，请重新获取");
      return;
  } else {
      if (isPerson) {
          caseData['caseName'] = userData[0].name;
          // caseData['phoneNum'] = userData[0].phoneNum;
          // caseData['forbidden'] = userData[0].forbidden;
          for (let index = 0; index < userData.length; index++) {
              userData[index].relation = "本人";
              userData[index].encryptMobile = realMobileList[index];
          }
          console.log(userData);
          caseData.selfList = userData;
          cas_num = userData[0].phoneNum;

      } else {
          //保存三方信息
          caseData.thirdList = userData;
          submitFlag = true;
      }
  }
}


//全部查看按钮方法
function showAllClick() {
  var table_type1 = document.querySelector("#owner");
  var table_type2 = document.querySelector("#userAdd");
  var table_item = table_type1 == null ? table_type2 : table_type1;
  if (table_item != null) {
      var tbody = table_item.querySelector("tbody");
      var trList = tbody.querySelectorAll("tr");
      for (let index = 0; index < trList.length; index++) {
          var tdList = trList[index].querySelectorAll("td");
          let buttonList = tdList[2].querySelectorAll("button");
          for (let i = 0; i < buttonList.length; i++) {
            if(buttonList[i].innerText === '查看全部'){
              buttonList[i].click();
              break;
            }
          }
      }
  } else {
      console.log("没有执行点击查看全部按钮");
  }
}


//获取三方信息接口请求
function getCustomerInfo() {

  GM_xmlhttpRequest({
    method: "post",
    url: `${c_person_info}?cas_num=${cas_num}&cas_name=${cas_name}&cas_mov_pho=${cas_mov_pho}&project=xiaomi`,
    headers: {
      "Content-Type": "application/x-www-form-urlencoded"
    },
    onload: function (res) {
      if (res.status == 200) {
        var data = JSON.parse(res.responseText + "");
        var responseData = data.data;
        var getInfoData = responseData[0];
        if(getInfoData){
          let {
            name,
            idCard,
            phoneNumber,
          } = getInfoData;
          let selfList = caseData.selfList;
          let phoneNumExist=false;
          selfList.foreach((item)=>{
            if(item.phoneNum === phoneNumber){
              phoneNumExist = true;
              return;
            }
          });
          //本人信息合并到总数据
          if(!phoneNumExist)
          {
            caseData.selfList.push({name:name,phoneNum:phoneNumber,relation:'本人',forbidden:0});
          }
          personInfo = [{
              name: '姓名',
              value: name
            },
            {
              name: '身份证号',
              value: idCard
            },
            {
              name: '手机号',
              value: phoneNumber
            },
          ];

          let relationData = getInfoData.relationList;
          let thirdList = caseData.thirdList;
          //三方信息合并到总数据
          relationData.foreach((item)=>{
            let existflag=false;
            for (let i = 0; i < thirdList.length; i++) {
              if(item.tripartitePhone === thirdList[i].phoneNum){
                existflag=true;
                break;
              }
            }
            if(!existflag){
              caseData.thirdList.push({name:item.tripartiteName,phoneNum:item.tripartitePhone,
              relation:item.relationShip,forbidden:0})
            }
          })
          relationInfo = relationData.map((item) => {
            return [{
                name: '姓名',
                value: item.tripartiteName
              },
              {
                name: '手机号',
                value: item.tripartitePhone
              },
              {
                name: '关系',
                value: item.relationShip
              }
            ];
          });
          InsertInfo(caseDetailAction);
        }
      }
    },
    onerror: function (err) {
      showAlert("请求数据错误");
    }
  });
}

//插入展示信息页面
function InsertInfo(parseItem) {
  GM_addStyle(`h4{
    margin: 0;
    padding: 0;
    color:#fff;
  }
  .insertData{
    max-width: 950px!important;
    min-height: 20vh;
    max-height: 30vh;
    overflow-y: auto;
    box-shadow: 1px 2px 3px #ddd;
    border: 1px solid #0678F4;
    background-color: #fff;
    font-size: 12px!important;
    margin: 100px auto;
    padding-bottom:20px;
  }
  .insertTitle{
    width: 100%;
    background-color: #0678F4;
    height:20px;
  }
  .personItem,.relationItem{
    display: flex;
    flex-wrap: wrap;
    margin: 0 20px;
    padding: 0px;
  }
  .personItem span,.relationItem span{
    border: 0.5px solid #0678F4;
    width: 200px;
    text-align: center;
  }
  .relationItem{
    margin-top: 10px;
  }
  .spanTitle{
    min-width: 80px!important;
    max-width:100px!important;
    font-weight: bold;
  }`);

  parseItem.innerHTML += `<div class="insertData">
      <h4 class="insertTitle">客户信息</h4>
      <h6>本人信息</h6>
      <div class="personItem">
      </div>
      <h6>三方信息</h6>
      <div class="relation">
      </div>
    </div>`;
  let personItem = document.querySelector(".personItem");
  for (let i = 0; i < personInfo.length; i++) {
    for (let key in personInfo[i]) {
      let item = personInfo[i][key];
      if(key === 'name')
        personItem.innerHTML+=`<span class="spanTitle">${item}</span>`
      else
        personItem.innerHTML+=`<span>${item}</span>`
    }
  }
  let relation = document.querySelector(".relation");
  for (let i = 0; i < relationInfo.length; i++) {
    let relationItem = document.createElement("div");
    relationItem.className = "relationItem";
    for (let j = 0; j < relationInfo[i].length; j++) {
      for (let key in relationInfo[i][j]) {
        let item = relationInfo[i][j][key];
        if(key === 'name')
          relationItem.innerHTML += `<span class="spanTitle">${item}</span>`;
        else
        relationItem.innerHTML += `<span>${item}</span>`;
      }
    }
    relation.appendChild(relationItem);
  }


}
var eleAlert;
//增加自定义弹框
function addAlert(){
  GM_addStyle(`.props{
    width: 400px;
    height: 100px;
    position: fixed;
    top: 20vh;
    left: 50%;
    transform: translateX(-200px);
    z-index:150;
  }
  .alertItem{
    position: absolute;
    width: 400px;
    top: 0px;
    left: 0px;
    border: 1px solid #0678F4;
    text-align: center;
    font-size:20px;
    color:#0678F4;
    background-color: #fff;
    box-shadow: 3px 5px 5px #ddd;
    display: block;
  }`);
  let alertEle = document.createElement("div");
  alertEle.className="props";
  eleAlert = document.body.insertBefore(alertEle,document.body.firstChild);
}
//显示消息弹框
function showAlert(text){
  console.log(eleAlert);
  let textEle = document.createElement("p");
  textEle.className="alertItem";
  textEle.innerText=text;
  eleAlert.appendChild(textEle);
  setTimeout(()=>{
    eleAlert.removeChild(textEle);
  },3000);
}